/**
 *
 * @param ruleName 校验规则名称 string
 * @param label 字段名称 string
 * @param required boolean
 * @param trigger string
 * @returns [{}]  array
 */
import Vue from 'vue';

Vue.prototype.vType = function (ruleName, label, required, trigger, param) {
	'use strict';
	required = required === undefined ? false : required;
	const formatSuffix = '';
	const requiredSuffix = '不能为空';
	let typeMap = {
		wbMoney: {tip:'，最高不能超过1000万元'},
		length12: {reg: /^.{12}$/, tip: '，长度为12位'},
		length18: {reg: /^.{18}$/, tip: '，长度为18位'},
		uscCode:{reg:/^([0-9A-Z]{18}|[0-9A-Z]{15})$/,tip:'格式不正确'},
		equalPassword: {reg: /^[a-zA-Z0-9_]\w{5,}$/, tip: '，两次输入的密码不一致'},
		minLength6: {reg: /^[a-zA-Z0-9_]\w{5,}$/, tip: '，不能小于6字符'},
		maxNumber8: {reg: /^\d{1,8}$/, tip: '，只能数字且不超过8位'},
		maxCharacter12: {reg: /^.{1,12}$/, tip: '，不超过12个字符'},
		maxCharacter19: {reg: /^.{1,19}$/, tip: '，长度不能超过19位'},
		bankPayAmount: {reg: /(^0\.[1-9]{1,2}$)|(^0\.[0-9][0-9]{1,1}$)/, tip: '需为(0~1)之间的小数'},
		companyName: {reg: /^.{1,48}$/, tip: '，不超过48个字符'},
		maxCharacter25: {reg: /^.{1,25}$/, tip: '，不超过25个字'},
		maxNumber50: {reg: /^[a-zA-Z0-9]{1,25}$/, tip: '，数字或字母不超过25'},
		maxCharacter64: {reg: /^.{1,64}$/, tip: '，不超过64个字符'},
		/*整数*/
		int: {reg: /^-?[0-9]+$/, tip: '，请输入整数'},
		/*正整数*/
		positiveInt: {reg: /^[0-9]+$/, tip: '，请输入正整数'},
		/*负整数*/
		negativeInt: {reg: /^-[0-9]+$/, tip: '，请输入负整数'},
		/*浮点数*/
		float: {reg: /^-?[0-9]*\.[0-9]+$/, tip: '，请输入小数'},
		/*正小数*/
		positiveFloat: {reg: /^[0-9]*\.[0-9]+$/, tip: '，请输入正小数'},
		/*负小数*/
		negativeFloat: {reg: /^-[0-9]*\.[0-9]+$/, tip: '，请输入负小数'},
		/*编码 拼音缩写+6位数字*/
		code: {reg: /^[a-zA-Z]{1,}[0-9]{6}$/, tip: '，编码由名称拼音缩写+6位数字组成'},
		/*利率 大于0小于100数字*/
		num100: {reg: /^100$|^(\d|[1-9]\d)(\.\d+)*$/, tip: '，请输入大于0小于100数字'},
		/*用户名 8到16位 数字、字母或字母数字组合*/
		username: {reg: /^(?!([a-zA-Z]+|\d+)$)[a-zA-Z\d]{8,16}$/, tip: '，请输入8-16位的数字字母组合'},// /^(?![^a-zA-Z]+$)(?!\D+$)/
		/*密码 */
		pwd: {
			reg: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
			tip: '为8-20位数字、字母组合'
		},
		/*纳税人识别号 15位到20位数字或字母*/
		nsrsbh: {reg: /^[a-zA-Z0-9-]{15,20}$/, tip: ''},
		/*邮政编码 6位数字*/
		yzbm: {reg: /^[0-9]{6}$/, tip: '，请输入6位数字的邮政编码'},
		/*其他证件号码 20 位之内的数字字母组合 */
		zjhm: {reg: /^([0-9A-Za-z]|[-]){0,20}$/, tip: '，请输入长度在20位之内的数字字母组合'},
		/*组织机构代码（必须为9位数字字母，字母为半角大写）*/
		zzjgdm: {reg: /^[A-Z0-9]{9}$/, tip: '，请输入9位数字和大写字母组合'},
		/*最大14位整数，最多两位小数金额*/
		money: {
			reg: /^(([-]?[0-9]{1,7}[.]{1}[0-9]{1,2})$|([-]?[0-9]{1,7})$)/,
			tip: '的整数最多7位、小数最多2位'
		},
		/*邮箱 */
		email: {
			reg: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
			tip: '格式不正确'
		},
		/*英文字母 大小写*/
		letter: {reg: /^[a-zA-Z]+$/i, tip: '，请输入英文字母'},
		/*数字字母组合*/
		letter_number: {reg: /^[a-zA-Z0-9]+$/i, tip: '，请输入英文字母和数字组合'},
		/*含有下划线的字母、数字或者数字字母组合*/
		letter_number_dash: {reg: /^[a-zA-Z0-9\-?]+$/i, tip: '，请输入下划线加英文字母和数字组合'},
		/*中文字符*/
		chinese: {reg: /^[\u4e00-\u9fa5]+$/, tip: '，请输入中文'},
		/*手机号码*/
		mobile: {reg: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, tip: '格式不正确'},
		/*固定电话*/
		tel: {reg: /^(0\d{2,3}-?){0,1}\d{7,8}$/, tip: '，请输入固话号码（区号可带可不带）'},
		/*身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X*/
		sfzhm: {reg: /(^\d{15}$)|(^\d{17}(\d|X)$)/, tip: '格式不正确'},
		sfzhm18: {
			reg: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
			tip: '请输入18位身份证号'
		},
		/*特殊字符  英文*/
		specialEn: {reg: /[`~!@#$%^&*()_+=<>?:"{},./;'[\]]/im, tip: '，不能包含英文特殊字符，如~、!、@、#、$、%、^、&、*等'},
		/*特殊字符  中文*/
		specialCn: {
			reg: /[~！@#￥%…&*=+（——）·：；“”‘、，|《。》？、【】[\]]/im,
			tip: '，不能包含中文特殊字符，如中文标点、·、！、#、￥、等'
		},
		/*url*/
		url: {
			reg: /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!-/]))?$/,
			tip: '，正确格式：http://www.baidu.com'
		}
	};
	//校验位的检测
	let checkParity = function (card) {
		//15位转18位
		card = change15To18(card);
		if (card.length === 18) {
			let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
			let cardTemp = 0, i;
			for (i = 0; i < 17; i++) {
				cardTemp += card.substr(i, 1) * arrInt[i];
			}
			return arrCh[cardTemp % 11] === card.substr(17, 1);
		}
		return false;
	};

	// 15位转18位身份证号
	let change15To18 = function (card) {
		if (card.length === 15) {
			let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
			let cardTemp = 0, i;
			card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
			for (i = 0; i < 17; i++) {
				cardTemp += card.substr(i, 1) * arrInt[i];
			}
			card += arrCh[cardTemp % 11];
			return card;
		}
		return card;
	};

	let rule = [];
	// 是否必填
	if (required) {
		rule.push({
			required: true,
			message: label + requiredSuffix,
			trigger: trigger || 'blur'
		});
	}
	// 单个的校验 转成 数组形式
	if (Object.prototype.toString.call(ruleName) === '[object String]') {
		ruleName = [ruleName];
	}
	// 通用 校验 方法
	let commonValidator = function (rule, value, callback) {
		let isValid;
		if (!value) {
			callback();
		} else {
			// 循环正则校验
			ruleName.forEach(v => {
				isValid = true;
				if (!!v) {
					if (v === 'equalPassword') {
						!(value === param) && (isValid = false);
					}
					if (v === 'wbMoney') {
						if(parseFloat(value) > 1000){
							isValid = false
						}else{
							if(value.toString().substring(0,1)=='0'){
								typeMap[v].tip = '，首位不能为0';
								isValid = false;
							}else{
								var index = value.toString().indexOf('.')
								if(index>=0){
									var temp = value.toString().substring(index+1,value.toString().length).toString().length;
									if(temp>6){
										typeMap[v].tip = '，小数点不能超过6位';
										isValid = false
									}
								}
							}
						}
					}else { // 其他使用正则方法
						!typeMap[v].reg.test(value) && (isValid = false);
					}
				}
				if (!isValid) {
					callback(new Error(label + formatSuffix + typeMap[v].tip));
					return false;
				} else {
					callback();
				}
			});
		}
	};
	rule.push({
		validator: commonValidator,
		trigger: trigger || 'blur'
	});
	return rule;
};
Vue.prototype.vMoney = {
	decode: function (num,place) {
		try {
			if(num==0||num=='0'||num=='0.0'||num=='0.00')
			{
				return num
			}
			//num = parseFloat(!!num ? num : '').toFixed(2);
			if(!!num){
				num = parseFloat(num).toFixed(place);
			}else{
				return ''
			}

			let index = num.toString().indexOf('.');
			if (index > -1) {
				let arrTemp = num.toString().split('.');
				return arrTemp[0].toString().replace(/(?=(?!(\b))(\d{3})+$)/g, ",") + '.' + arrTemp[1]
			} else {
				return num.toString().replace(/(?=(?!(\b))(\d{3})+$)/g, ",");
			}
		} catch (e) {
			console.log(e);
		}
	},
	undecode: function (num) {
		try {
			num = !!num ? num : '';
			return num.toString().replace(/,/g, '');
		} catch (e) {
			console.log(e);
		}
	}
}
Vue.prototype.vTool = {

	removeClass(ele, cls) {
		if (Vue.prototype.vTool.hasClass(ele, cls)) {
			var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
			ele.className = ele.className.replace(reg, " ");
		}
	},
	addClass(ele, cls) {
		if (!Vue.prototype.vTool.hasClass(ele, cls)) ele.className += " " + cls;
	},
	hasClass(ele, cls) {
		return ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
	},
	showSingleError() {
		let _this = this;
		let $domParent = document.getElementsByClassName('is-error');
		let $domChild = document.getElementsByClassName('el-form-item__error');
		for (let i = 0; i < $domParent.length; i++) {
			if (i != 0) {
				$domChild[i].style.display = 'none';
				Vue.prototype.vTool.addClass($domParent[i], 'is-llt-suc');
			} else {
				$domChild[i].style.display = 'block';
				Vue.prototype.vTool.removeClass($domParent[i], 'is-llt-suc');
			}
		}
		document.getElementsByClassName('is-error')[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
	},
	getCode(TIME_COUNT, callback, dom) {

		let count = TIME_COUNT;
		let timer = setInterval(() => {
			if (count > 0 && count <= TIME_COUNT) {
				if (!!dom) {
					dom.innerHTML = count + "秒后再试";
				}
				count--;
			} else {
				clearInterval(timer);
				timer = null;
				callback();
			}
		}, 1000);
		return timer;
	}
}

Vue.prototype.formatMoney = function (s, type) {
	// if (/[^0-9\.]/.test(s))
	//     return "0.00";
	// if(isNaN(val)) return ''
	if (s == null || s == "" || s == 0)
		return "0.00";
	s = Number(s)
	var result = s;
	if (s < 0) {
		s = 0 - s;
	}
	if (isNaN(s)) return ''
	s = s.toString().replace(/^(\d*)$/, "$1.");
	s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
	s = s.replace(".", ",");
	var re = /(\d)(\d{3},)/;
	while (re.test(s))
		s = s.replace(re, "$1,$2");
	s = s.replace(/,(\d\d)$/, ".$1");
	if (type == 0) {// 不带小数位(默认是有小数位)
		var a = s.split(".");
		if (a[1] == "00") {
			s = a[0];
		}
	}
	if (result < 0) {
		s = '-' + s
	}
	return s;
}


